package ex01.pyrmont;

import java.io.InputStream;
import java.io.IOException;

public class Request {

    /**
     * 对象由socket获取到的outputStream
     */
    private InputStream input;
    private String uri;

    public Request(InputStream input) {
        this.input = input;
    }

    public void parse() {
        // Read a set of characters from the socket
        StringBuffer request = new StringBuffer(2048);
        int i;
        byte[] buffer = new byte[2048];
        try {
            //将数据读到buffer中去
            i = input.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
            i = -1;
        }
        for (int j = 0; j < i; j++) {
            request.append((char) buffer[j]);
        }
        System.out.print(request.toString());
        uri = parseUri(request.toString());
    }

    /**
     * String::indexOf返回指定字符在字符串中第一次出现处的索引
     *
     * @param requestString
     * @return
     */
    private String parseUri(String requestString) {
        int index1, index2;
        System.out.println("============请求报文【开始】=======================");
        System.out.println(requestString);
        System.out.println("============请求报文【结束】=======================");

        index1 = requestString.indexOf(' ');
        if (index1 != -1) {
            index2 = requestString.indexOf(' ', index1 + 1);
            if (index2 > index1) {
                //截取得到 index.html
                String requestUri = requestString.substring(index1 + 1, index2);
                System.out.println("============请求URI【开始】=======================");
                System.out.println(requestUri);
                System.out.println("============请求URI【结束】=======================");
                return requestUri;
            }
        }
        return null;
    }

    public String getUri() {
        return uri;
    }

}
//【parseUri】 requestString
//GET /index.html HTTP/1.1
//Host: localhost:8081
//Connection: keep-alive
//Cache-Control: max-age=0
//sec-ch-ua: "Not?A_Brand";v="8", "Chromium";v="108", "Microsoft Edge";v="108"
//sec-ch-ua-mobile: ?0
//sec-ch-ua-platform: "Windows"
//Upgrade-Insecure-Requests: 1
//User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.46
//Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
//Sec-Fetch-Site: none
//Sec-Fetch-Mode: navigate
//Sec-Fetch-User: ?1
//Sec-Fetch-Dest: document
//Accept-Encoding: gzip, deflate, br
//Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
//Cookie: Idea-5af8bf2b=a66bd1e3-f14d-489a-9ec3-422f65b10700

